// 定义统一的尺寸常量
const PAGE_WIDTH = 800;
const PAGE_HEIGHT = 1000;
const CONTENT_WIDTH = 720;
const CONTENT_HEIGHT = 900;
const PAGE_PADDING_TOP = 60;
const PAGE_PADDING_BOTTOM = 60;
const PAGE_PADDING_SIDES = 40;

class BookAdmin {
    constructor() {
        this.editor = null;
        this.coverImage = null;
        this.initEditor();
        this.loadCoverImage(); // 加载已保存的封面图
        this.bindEvents();
    }

    // 加载已保存的封面图
    loadCoverImage() {
        try {
            const savedCover = localStorage.getItem('bookCover');
            if (savedCover) {
                this.coverImage = savedCover;
            }
        } catch (error) {
            console.error('加载封面图失败:', error);
        }
    }

    // 处理封面图上传
    async handleCoverImage(event) {
        const file = event.target.files[0];
        if (!file) return;

        try {
            // 将文件转换为 base64
            const reader = new FileReader();
            reader.onload = (e) => {
                this.coverImage = e.target.result;
                // 保存封面图到 localStorage
                localStorage.setItem('bookCover', this.coverImage);
                alert('封面图设置成功！');
            };
            reader.readAsDataURL(file);
        } catch (error) {
            console.error('封面图处理失败:', error);
            alert('封面图处理失败: ' + error.message);
        }
    }

    // 获取数据时也获取封面图
    async getData() {
        try {
            const dataStr = localStorage.getItem('bookData');
            const coverImage = localStorage.getItem('bookCover');
            
            if (dataStr) {
                const data = JSON.parse(dataStr);
                return {
                    ...data,
                    coverImage: coverImage || null
                };
            }
            return {
                title: "我的电子书",
                content: "",
                coverImage: null
            };
        } catch (error) {
            console.error('获取数据失败:', error);
            throw error;
        }
    }

    // 保存数据时也保存封面图
    async saveData(data) {
        try {
            if (this.coverImage) {
                localStorage.setItem('bookCover', this.coverImage);
            }
            localStorage.setItem('bookData', JSON.stringify(data));
        } catch (error) {
            console.error('保存数据失败:', error);
            throw error;
        }
    }

    // 导入数据时也处理封面图
    async importData(event) {
        try {
            const file = event.target.files[0];
            if (!file) return;

            const text = await file.text();
            const importedData = JSON.parse(text);

            // 验证数据格式
            if (!importedData.content) {
                throw new Error('无效的数据格式');
            }

            // 处理导入的数据
            const data = {
                title: importedData.title || "我的电子书",
                content: importedData.content,
                updatedAt: new Date().toISOString()
            };

            // 如果有封面图也导入
            if (importedData.coverImage) {
                this.coverImage = importedData.coverImage;
                localStorage.setItem('bookCover', importedData.coverImage);
            }

            // 保存数据
            await this.saveData(data);

            // 更新编辑器内容
            if (this.editor) {
                this.editor.root.innerHTML = data.content;
            }

            alert('数据导入成功！');
        } catch (error) {
            console.error('导入失败:', error);
            alert('导入失败: ' + error.message);
        } finally {
            event.target.value = '';
        }
    }

    // 导出数据时也导出封面图
    async exportData() {
        try {
            const data = await this.getData();

            // 创建导出对象
            const exportData = {
                title: data.title || "我的电子书",
                content: data.content,
                coverImage: this.coverImage, // 包含封面图
                updatedAt: new Date().toISOString()
            };

            // 转换为JSON字符串
            const jsonStr = JSON.stringify(exportData, null, 2);

            // 创建Blob
            const blob = new Blob([jsonStr], { type: 'application/json' });

            // 创建下载链接
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `book_data_${new Date().getTime()}.json`;

            // 触发下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);

            alert('数据导出成功！');
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败: ' + error.message);
        }
    }

    // 绑定事件
    bindEvents() {
        document.getElementById('saveBtn').addEventListener('click', () => this.saveContent());
        document.getElementById('exportBtn').addEventListener('click', () => this.exportBook());
        document.getElementById('exportDataBtn').addEventListener('click', () => this.exportData());
        document.getElementById('importBtn').addEventListener('click', () => this.triggerImport());
        document.getElementById('importFile').addEventListener('change', (e) => this.importData(e));
        document.getElementById('coverImage').addEventListener('change', (e) => this.handleCoverImage(e));
    }

    // 初始化编辑器
    async initEditor() {
        try {
            const editorElement = document.getElementById('bookEditor');
            if (!editorElement) {
                throw new Error('Editor element not found');
            }

            // 获取已保存的内容
            const data = await this.getData();

            // 创建编辑器实例
            this.editor = await createEditor(editorElement, data.content || '');

            if (!this.editor) {
                throw new Error('Failed to create editor instance');
            }
        } catch (error) {
            console.error('编辑器初始化失败:', error);
            alert('编辑器初始化失败: ' + error.message);
        }
    }

    // 保存内容
    async saveContent() {
        try {
            if (!this.editor) {
                throw new Error('编辑器实例不存在');
            }

            const content = this.editor.root.innerHTML;

            // 保存数据
            const data = await this.getData();
            data.content = content;
            data.updatedAt = new Date().toISOString();

            await this.saveData(data);
            alert('保存成功！');
        } catch (error) {
            console.error('保存失败:', error);
            alert('保存失败: ' + error.message);
        }
    }

    // 修改进度遮罩的创建方法
    createProgressMask() {
        const mask = document.createElement('div');
        mask.className = 'progress-mask';
        mask.innerHTML = `
            <div class="progress-container">
                <div class="progress-text">正在导出电子书...</div>
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <div class="progress-text">
                    已处理 <span class="current-page">0</span> 页
                </div>
            </div>
        `;
        document.body.appendChild(mask);

        // 返回带有更新方法的对象
        return {
            mask,
            updateProgress: (current, total) => {
                console.log('更新进度:', current, total); // 添加日志
                const percentage = (current / total) * 100;
                const fill = mask.querySelector('.progress-fill');
                const currentPage = mask.querySelector('.current-page');
                if (fill) fill.style.width = `${percentage}%`;
                if (currentPage) currentPage.textContent = current;
            },
            remove: () => {
                document.body.removeChild(mask);
            }
        };
    }

    // 导出电子书
    async exportBook() {
        const progress = this.createProgressMask();
        let container = null;
        let tempContainer = null;
        
        try {
            const data = await this.getData();

            // 创建 ZIP 文件
            const zip = new JSZip();
            const normalFolder = zip.folder("files/mobile");
            const thumbFolder = zip.folder("files/thumb");

            // 创建一个临时容器来计算内容
            tempContainer = document.createElement('div');  // 赋值给之前声明的变量
            tempContainer.style.width = `${CONTENT_WIDTH}px`;
            tempContainer.style.position = 'absolute';
            tempContainer.style.left = '-9999px';
            tempContainer.innerHTML = data.content;
            document.body.appendChild(tempContainer);

            // 创建实际渲染容器
            container = document.createElement('div');
            container.style.width = `${PAGE_WIDTH}px`;
            container.style.height = `${PAGE_HEIGHT}px`;
            container.style.position = 'absolute';
            container.style.left = '-9999px';
            container.style.padding = `${PAGE_PADDING_TOP}px ${PAGE_PADDING_SIDES}px ${PAGE_PADDING_BOTTOM}px`;
            container.style.boxSizing = 'border-box';
            container.style.backgroundColor = '#ffffff';
            container.style.overflow = 'hidden';
            document.body.appendChild(container);

            let currentPage = 0;
            let remainingContent = tempContainer.cloneNode(true);

            // 如果有封面图,先处理封面图
            if (this.coverImage) {
                const coverImg = await this.processImage(this.coverImage);
                normalFolder.file('1.jpg', coverImg.normal.split('base64,')[1], { base64: true });
                thumbFolder.file('1.jpg', coverImg.thumb.split('base64,')[1], { base64: true });
                currentPage = 1;
            }

            // 分页渲染
            while (remainingContent.childNodes.length > 0) {
                // 清空容器
                container.innerHTML = '';
                
                // 尝试添加内容直到超出容器高度
                while (remainingContent.childNodes.length > 0) {
                    const node = remainingContent.childNodes[0];
                    container.appendChild(node.cloneNode(true));
                    
                    // 检查是否超出容器高度
                    if (container.scrollHeight > container.clientHeight) {
                        // 如果超出，移除最后一个节点
                        container.removeChild(container.lastChild);
                        break;
                    }
                    // 如果没超出，从剩余内容中移除该节点
                    remainingContent.removeChild(node);
                }

                // 使用 html2canvas 渲染当前页
                const canvas = await html2canvas(container, {
                    scale: 2,
                    width: PAGE_WIDTH,
                    height: PAGE_HEIGHT,
                    backgroundColor: '#ffffff'
                });

                // 生成正常大小的图片
                const normalImgData = canvas.toDataURL('image/jpeg', 0.8);
                normalFolder.file(`${currentPage + 1}.jpg`, normalImgData.split('base64,')[1], { base64: true });

                // 生成缩略图
                const thumbCanvas = document.createElement('canvas');
                const thumbCtx = thumbCanvas.getContext('2d');
                thumbCanvas.width = 200;
                thumbCanvas.height = 282;
                thumbCtx.drawImage(canvas, 0, 0, thumbCanvas.width, thumbCanvas.height);
                const thumbImgData = thumbCanvas.toDataURL('image/jpeg', 0.6);
                thumbFolder.file(`${currentPage + 1}.jpg`, thumbImgData.split('base64,')[1], { base64: true });

                currentPage++;
                progress.updateProgress(currentPage, Math.ceil(tempContainer.scrollHeight / PAGE_HEIGHT));
            }

            // 分页渲染完成后，生成 book_content.js
            const bookContentJS = `var BOOK_CONTENT = ${JSON.stringify({
                totalPages: currentPage,
                updatedAt: new Date().toISOString()
            }, null, 2)};`;

            // 将 book_content.js 添加到 ZIP 根目录
            zip.file("book_content.js", bookContentJS);

            // 生成并下载 ZIP
            const content = await zip.generateAsync({ type: "blob" });
            const url = URL.createObjectURL(content);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'book-images.zip';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);

            alert('导出成功,请把文件解压后覆盖前端对应文件夹！');

        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败: ' + error.message);
        } finally {
            // 清理所有容器
            if (container && container.parentNode) {
                container.parentNode.removeChild(container);
            }
            if (tempContainer && tempContainer.parentNode) {
                tempContainer.parentNode.removeChild(tempContainer);
            }
            if (progress) {
                progress.remove();
            }
        }
    }

    // 触发文件选择
    triggerImport() {
        document.getElementById('importFile').click();
    }

    // 处理图片方法
    async processImage(imgData) {
        // 创建图片元素
        const img = new Image();
        img.src = imgData;
        await new Promise(resolve => img.onload = resolve);

        // 处理正常大小图片
        const normalCanvas = document.createElement('canvas');
        normalCanvas.width = 800;
        normalCanvas.height = 1122;
        const normalCtx = normalCanvas.getContext('2d');
        normalCtx.fillStyle = '#ffffff';
        normalCtx.fillRect(0, 0, normalCanvas.width, normalCanvas.height);
        this.drawImageProp(normalCtx, img, 0, 0, normalCanvas.width, normalCanvas.height);

        // 处理缩略图
        const thumbCanvas = document.createElement('canvas');
        thumbCanvas.width = 200;
        thumbCanvas.height = 282;
        const thumbCtx = thumbCanvas.getContext('2d');
        thumbCtx.fillStyle = '#ffffff';
        thumbCtx.fillRect(0, 0, thumbCanvas.width, thumbCanvas.height);
        this.drawImageProp(thumbCtx, img, 0, 0, thumbCanvas.width, thumbCanvas.height);

        return {
            normal: normalCanvas.toDataURL('image/jpeg', 0.8),
            thumb: thumbCanvas.toDataURL('image/jpeg', 0.6)
        };
    }

    // 辅助方法:保持比例绘制图片
    drawImageProp(ctx, img, x, y, w, h) {
        const imgRatio = img.width / img.height;
        const canvasRatio = w / h;
        let drawWidth, drawHeight, offsetX = 0, offsetY = 0;

        if (imgRatio > canvasRatio) {
            drawHeight = h;
            drawWidth = h * imgRatio;
            offsetX = (w - drawWidth) / 2;
        } else {
            drawWidth = w;
            drawHeight = w / imgRatio;
            offsetY = (h - drawHeight) / 2;
        }

        ctx.drawImage(img, x + offsetX, y + offsetY, drawWidth, drawHeight);
    }
}

// 确保类定义在全局作用域
window.BookAdmin = BookAdmin; 